package auth

import (
	"kms-backend/config"
	"kms-backend/utils/cryptmd5"
	"kms-backend/utils/db"
	"kms-backend/utils/jwtutils"
	"kms-backend/utils/logs"

	"github.com/gin-gonic/gin"
)

type UserInfo struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Phone    string `json:"phone"`
}

type User struct {
	// gorm.Model
	ID       int64  `gorm:"type:bigint(20);column:id;primary_key"`
	Username string `gorm:"type:varchar(128);column:username"`
	PHONE    string `gorm:"type:varchar(50);column:phonenumber"`
	Password string `gorm:"type:char(32);column:password"`
}

// 登录逻辑

func Login(r *gin.Context) {
	// 获取前端传递的用户名和密码
	// {"username": "bigberg","phone": "15168330978", "password": "123654"}
	returnData := config.NewReturnData()
	userinfo := UserInfo{}
	if err := r.ShouldBindJSON(&userinfo); err != nil {
		returnData.Message = err.Error()
		returnData.Status = 401
		r.JSON(200, returnData)
		return
	}
	// 密码md5加密

	passwd := cryptmd5.MD5(userinfo.Password)
	//fmt.Println(passwd)
	//logs.Debug(map[string]interface{}{"手机号": userinfo.Phone, "密码": passwd}, "开始接收用户信息")

	// 验证用户名和密码是否正确

	// 获取数据库用户信息
	var user User
	db := db.GetDB()
	db.Where("phonenumber = ?", userinfo.Phone).First(&user)
	//fmt.Println(user)
	if user.PHONE == userinfo.Phone && user.Password == passwd {
		// 认证成功
		// 生产jwt token
		ss, err := jwtutils.GenToken(userinfo.Phone)
		if err != nil {
			returnData.Message = "生成token失败"
			returnData.Status = 401
			logs.Error(map[string]interface{}{"手机号": userinfo.Phone, "错误信息": err.Error()}, "生成token失败")
			r.JSON(200, returnData)
			return
		}
		logs.Info(map[string]interface{}{"手机号": userinfo.Phone}, "登录成功")
		returnData.Data["token"] = ss
		returnData.Message = "登录成功"
		r.JSON(200, returnData)
		return
	} else {
		// 用户名和密码错误
		returnData.Message = "用户名和密码错误"
		returnData.Status = 401
		r.JSON(200, returnData)
	}
	//fmt.Println(user)
}

// 登出逻辑

func Logout(r *gin.Context) {
	// 退出
	returnData := config.NewReturnData()
	returnData.Message = "用户退出成功"
	r.JSON(200, returnData)
	logs.Debug(nil, "用户已退出")

}
